const FORMAT = require('../../api/util.js')
import API from '../../api/api.js'
import Dialog from '../../lib/vant-weapp/dialog/dialog';
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    currArticleId: "",
    currArticleData: {},
    currBiMing: "",
    mode: "",
    huatimode: "",
    readOnly: false,
    placeholder: '此为富文本编辑器，段落【首行缩进】系统会自动添加，可编辑标题、加粗、换行、插入图片等，开始输入信件内容...',
    editorHeight: 300,
    keyboardHeight: 0,
    isIOS: false,
    commentNeiRong: "",
    xinJianShuJu: {
      shouJianRenOpenid: "",
      shouJianRenBiMing: "",
      faJianRenBiMing: "",
      neiRong: "",
      jianJie: "",
      chuangJianShiJian: "",
      touXiangUrl: "",
      faJianRenXinFengUrl: "",
      status: 0,
      xinJianImagesList: []
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.setNavigationBarTitle({
      title: '写信'
    })
    let currPerson = wx.getStorageSync('currPerson')
    this.setData({
      shouJianRenBiMing: currPerson.biMing
    })
    if ('mode' in options) {
      this.data.mode = options.mode
    }
    this.data.xinJianShuJu.shouJianRenBiMing = currPerson.biMing
    this.data.xinJianShuJu.shouJianRenOpenid = currPerson.openid
    if (this.data.xinJianShuJu.shouJianRenOpenid == "") {
      wx.setStorageSync('currXinJian', this.data.xinJianShuJu)
    }
    const platform = wx.getSystemInfoSync().platform
    const isIOS = platform === 'ios'
    this.setData({
      isIOS
    })
    const that = this
    this.updatePosition(0)
    let keyboardHeight = 0
    wx.onKeyboardHeightChange(res => {
      if (res.height === keyboardHeight) return
      const duration = res.height > 0 ? res.duration * 1000 : 0
      keyboardHeight = res.height
      setTimeout(() => {
        wx.pageScrollTo({
          scrollTop: 0,
          success() {
            that.updatePosition(keyboardHeight)
            that.editorCtx.scrollIntoView()
          }
        })
      }, duration)

    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let data = wx.getStorageSync('currXinJian')
    if (data != "") {
      this.data.xinJianShuJu = data
    }
  },


  updatePosition(keyboardHeight) {
    const toolbarHeight = 50
    const {
      windowHeight,
      platform
    } = wx.getSystemInfoSync()
    let editorHeight = keyboardHeight > 0 ? (windowHeight - keyboardHeight - toolbarHeight) : windowHeight
    this.setData({
      editorHeight,
      keyboardHeight
    })
  },
  calNavigationBarAndStatusBar() {
    const systemInfo = wx.getSystemInfoSync()
    const {
      statusBarHeight,
      platform
    } = systemInfo
    const isIOS = platform === 'ios'
    const navigationBarHeight = isIOS ? 44 : 48
    return statusBarHeight + navigationBarHeight
  },
  onEditorReady() {
    const that = this
    let tempdata = wx.getStorageSync('currXinJian')
    that.createSelectorQuery().select('#editor').context(function (res) {
      that.editorCtx = res.context
      if (tempdata.tiMu != "" || tempdata.leiXing != "" || tempdata.neiRong != "") {
        that.editorCtx.setContents({
          html: tempdata.neiRong
        })
      }
    }).exec()
  },
  blur() {
    this.editorCtx.blur()
  },
  format(e) {
    let {
      name,
      value
    } = e.target.dataset
    if (!name) return
    this.editorCtx.format(name, value)

  },
  onStatusChange(e) {
    const formats = e.detail
    this.setData({
      formats
    })
  },
  insertDivider() {
    this.editorCtx.insertDivider({
      success: function () {}
    })
  },
  clear() {
    this.editorCtx.clear({
      success: function (res) {}
    })
  },
  removeFormat() {
    this.editorCtx.removeFormat()
  },
  insertDate() {
    const date = new Date()
    const formatDate = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`
    this.editorCtx.insertText({
      text: formatDate
    })
  },

  getImageInfo: function (path) {
    return new Promise(function (resolve, reject) {
      wx.getImageInfo({
        src: path,
        success(res) {
          resolve(res.type)
        },
        fail: err => {
          reject("获取数据出错了，请重试！")
          console.error(err)
        }
      })
    })
  },

  async insertImage() {
    const that = this
    wx.chooseImage({
      count: 1,
      async success(res) {
        let tempfile = res.tempFilePaths[0]
        wx.showLoading({
          title: '正在检测图片内容...',
          mask: true
        })
        await API.checkImageContent(res.tempFilePaths[0]).then(async res => {
          if (res.result.errCode == 87014) {
            wx.showToast({
              title: '您的图片内有违规内容，请更换图片，请谅解。',
              icon: "none"
            })
            wx.hideLoading()
            return
          }
          wx.hideLoading()
          wx.showLoading({
            title: '正在加载...',
            mask: true
          })
          that.getImageInfo(tempfile).then(res => {
            let fileName = "xinjianimages/" + new Date().getTime() + "." + res
            wx.cloud.uploadFile({
              cloudPath: fileName,
              filePath: tempfile,
            }).then(res => {
              that.data.xinJianShuJu.xinJianImagesList.push(res.fileID)
              that.editorCtx.insertImage({
                src: res.fileID,
                width: '100%',
                success: function () {
                  wx.hideLoading()
                  wx.showToast({
                    title: '图片插入成功！',
                    icon: "success",
                    duration: 2000
                  })
                }
              })
            })
          }).catch(error => {
            // handle error
          })
        })
      }
    })
  },
  onFocus: function (e) {

  },
  onInput: function (e) {
    this.data.xinJianShuJu.jianJie = e.detail.text.substring(0, 50)
    this.data.xinJianShuJu.neiRong = e.detail.html
    this.data.commentNeiRong = e.detail.text
    this.setData({
      neiRong: e.detail.html
    })
  },
  onBlur: function (e) {},

  onFaBu: async function (e) {
    let userInfo = wx.getStorageSync('userInfo')
    let data = this.data.xinJianShuJu
    if (userInfo == "") {
      wx.showToast({
        title: '用户信息丢失，请重新登录。',
        icon: 'none'
      })
      return
    }
    await API.checkWenZhiNeiRong(this.data.neiRong).then(res => {
      if (res.result.errCode === 87014) {
        wx.showToast({
          title: '您的文章内有违规内容，请更换图片，请谅解。',
          icon: "none"
        })
        wx.hideLoading()
        return
      }
      wx.hideLoading()
      data.faJianRenBiMing = userInfo.biMing
      data.chuangJianShiJian = FORMAT.formatDay(Math.floor(new Date().getTime() / 1000))
      data.faJianRenXinFengUrl = userInfo.faJianRenXinFengUrl
      data.touXiangUrl = userInfo.touXiang
      let content = data.neiRong.replace(/<p/g, '<p style="text-indent: 1em;" ').replace(/<img/g, '<img style="text-indent: none !important;" ')
      data.neiRong = content
      if (this.data.mode == "send") {
        Dialog.confirm({
            title: '发送信件',
            message: '请确定是否发送信件给【' + data.shouJianRenBiMing + '】',
          })
          .then(() => {
            if (data.shouJianRenOpenid == userInfo._openid) {
              wx.showToast({
                title: '不能给自己写信',
                icon: 'none'
              })
              return
            }
            if (data.neiRong == "") {
              wx.showToast({
                title: '发送内容不能为空。',
                icon: 'none'
              })
              return
            }
            wx.showLoading({
              title: '加载中...',
              mask: true
            })
            API.tianJiaShuJu('xinjian', data).then(res => {
              wx.removeStorageSync('currPerson')
              this.clear()
              wx.hideLoading()
              wx.navigateTo({
                url: "/pages/xinjiandetail/xinjiandetail?curTab=4&id=" + res
              })
            })
          })
          .catch(() => {
            wx.showToast({
              title: '已经取消发送信件。',
              icon: 'none'
            })
          })
      }
      if (this.data.mode == "reply") {
        Dialog.confirm({
            title: '回复信件',
            message: '请确定是否回复信件给【' + data.shouJianRenBiMing + '】',
          })
          .then(() => {
            let currPerson = wx.getStorageSync('currPerson')
            if (data._openid == userInfo._openid) {
              wx.showToast({
                title: '不能给自己写信',
                icon: 'none'
              })
              return
            }
            if (data.neiRong == "") {
              wx.showToast({
                title: '发送内容不能为空。',
                icon: 'none'
              })
              return
            }
            wx.showLoading({
              title: '加载中...',
              mask: true
            })
            API.tianJiaShuJu('xinjian', data).then(async res => {
              await API.updateXinJianStatus(currPerson._id, 2)
              wx.removeStorageSync('currXinJian')
              wx.removeStorageSync('currPerson')
              wx.hideLoading()
              wx.navigateBack({
                delta: 1
              })
              wx.redirectTo({
                url: "/pages/xinjiandetail/xinjiandetail?curTab=3&id=" + res
              })
            })
          })
          .catch(() => {
            wx.showToast({
              title: '已经取消发送信件。',
              icon: 'none'
            })
          })
      }
    })
  },

  onSave: function (e) {
    wx.showToast({
      title: '临时数据已保存草稿,点击发布后清理草稿。',
      icon: "none",
      duration: 2000
    })
    wx.setStorageSync('currXinJian', this.data.xinJianShuJu)
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let shareimages = app.globalData.shareimages
    let index = Math.floor(Math.random() * 5)
    return {
      title: '一个真正匿名的心情小程序',
      imageUrl: shareimages[index],
      path: '/pages/index/index'
    }
  },
  onShareTimeline: function () {
let shareimages = app.globalData.shareimages
    let index = Math.floor(Math.random() * 5)
    return {
      title: '一个真正匿名的心情小程序',
      imageUrl: shareimages[index]
    }
  }
})